package com.atao.baokede.controller;

import com.atao.baokede.pojo.Address;
import com.atao.baokede.pojo.Result;
import com.atao.baokede.service.AddressService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * 用户地址层
 */
@RestController
@RequestMapping("/addresses")
public class AddressController {

    @Autowired
    private AddressService addressService;

    /**
     * 添加地址
     * @param address 地址信息类
     * @return
     */
    @PostMapping
    public Result addAddress(@Validated @RequestBody Address address) {
        addressService.addAddressWithCurrentUser(address);
        return Result.success();
    }

    /**
     * 修改地址
     * @param id 地址id
     * @param address 地址信息类
     * @return 无
     */
    @PutMapping("/{id}")
    public Result updateAddress(@PathVariable Long id, @Validated @RequestBody Address address) {
        address.setId(id);
        addressService.updateAddressWithCurrentUser(address);
        return Result.success();
    }

    /**
     * 删除地址
     * @param id 地址id
     * @return 无
     */
    @DeleteMapping("/{id}")
    public Result deleteAddress(@PathVariable Long id) {
        addressService.deleteAddressWithCurrentUser(id);
        return Result.success();
    }

    /**
     * 获取当前用户的所有地址
     * @return 地址列表
     */
    @GetMapping
    public Result<List<Address>> getAddressList() {
        List<Address> addresses = addressService.getAddressesWithCurrentUser();
        return Result.success(addresses);
    }

    /**
     * 设置默认地址
     * @param id 地址id
     * @return  无
     */
    @PutMapping("/{id}/default")
    public Result setDefaultAddress(@PathVariable Long id) {
        addressService.setDefaultAddressWithCurrentUser(id);
        return Result.success();
    }
}